package com.hjimi.ski.view.service;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.hjimi.ski.app.MyApplication;
import com.hjimi.ski.bean.SyncImageListBean;
import com.hjimi.ski.utils.ImageDownloader;
import com.hjimi.ski.utils.Mutils;
import com.hjimi.ski.utils.SDFileHelper;
import com.hjimi.ski.utils.SdcardUtils;
import com.hjimi.ski.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created By 孙岩
 * on 2023/10/12
 */
public class MyImageService extends Service {
    private Handler handler;
    @Override
    public void onCreate() {
        super.onCreate();

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent!=null){
            List<SyncImageListBean.DataBean> list = (List<SyncImageListBean.DataBean>) intent.getSerializableExtra("beanList");
            initData(list);
        }

        return super.onStartCommand(intent, flags, startId);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initData(List<SyncImageListBean.DataBean> list) {
        //线上的集合
        List<String> online = new ArrayList<>();
        online.clear();
        //线下的集合
        List<String> onDown = SdcardUtils.getImageNameFromSD();
        Log.d("sunyan", "线下的集合==" + onDown.toString());
        //给线上的带id和md5url集合赋值
        for (int i = 0; i < list.size(); i++) {
            String tem = list.get(i).getId() + "@" + Mutils.md5(list.get(i).getImageUrl()) + ".jpg";
            if(!list.get(i).getBgm_config().getBgm_url().equals("")){
                String ten = list.get(i).getId() + "@" + Mutils.md5(list.get(i).getBgm_config().getBgm_url()) + ".mp3";
                online.add(ten);
            }

            online.add(tem);

        }
        Log.d("sunyan", "线上的集合==" + online.toString());
        //线上的集合跟线下集合出差 获取到需要下载的不带路径的数据（只有本地图片名称）
        Set<String> setOnDown = new HashSet<>(onDown);
        List<String> down1List = online.stream()
                .filter(i -> !setOnDown.contains(i))
                .collect(Collectors.toList());

        //执行下载操作
        List<String> downUrl = SdcardUtils.imageDown(list, down1List);
        Log.d("sunyan", "需要下载downUrl的集合=111111111111111111111=" + downUrl.toString());
        if (downUrl.size() > 0) {
            for (int i = 0; i < downUrl.size(); i++) {
//                SDFileHelper.savePicture(MyApplication.getInstance().getApplicationContext(), downUrl.get(i).split("@")[1], downUrl.get(i).split("@")[0] + "@" + Mutils.md5(downUrl.get(i).split("@")[1]) + ".jpg");
                new ImageDownloader(new Handler(Looper.getMainLooper()){
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        switch (msg.what){
                            case 1:
                                Log.d("sunyan","下载完成");
                                break;

                            case 2:
                                Log.d("sunyan","下载失败");
                                break;
                            case 3:
                                Log.d("sunyan","下载出错"+msg.obj);
                                break;
                        }
                        super.handleMessage(msg);
                    }
                }).downloadImage(downUrl.get(i).split("@")[1],"/storage/emulated/0/Pic/app/"+downUrl.get(i).split("@")[0] + "@" + Mutils.md5(downUrl.get(i).split("@")[1]));

                Log.d("sunyan","url======="+downUrl.get(i).split("@")[1]);
                Log.d("sunyan","fileName======="+"/storage/emulated/0/Pic/app/"+downUrl.get(i).split("@")[0] + "@" + Mutils.md5(downUrl.get(i).split("@")[1]) + ".jpg");
            }
        }

        Log.d("sunyan", "需要下载downUrl的集合==" + downUrl.toString());

        //线上的集合跟线下集合出差 获取到需要删除的不带路径的数据（只有本地图片名称）
        Set<String> setDelete = new HashSet<>(online);
        List<String> deleteList = onDown.stream()
                .filter(i -> !setDelete.contains(i))
                .collect(Collectors.toList());
        Log.d("sunyan", "需要删除的集合========1=" + deleteList.toString());
        //执行删除操作
        if (deleteList.size() > 0) {
            for (int i = 0; i < deleteList.size(); i++) {
                Log.d("sunyan", "执行删除操作==");
                if(!deleteList.get(i).endsWith("mp4")){
                    SdcardUtils.deleteSingleFile(this, deleteList.get(i));
                }
            }
        }
    }
}
